package com.motong.gongdan.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.motong.gongdan.entity.*;
import com.motong.gongdan.mapper.WagesMapper;
import com.motong.gongdan.util.LoginUtil;
import com.motong.gongdan.util.StringUtil;
import com.motong.gongdan.vo.system.otherVo.CustomFieldVo;
import com.motong.gongdan.vo.system.otherVo.WageReportVo;
import com.motong.gongdan.vo.resp.MissionListResp;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.*;

/**
 * @author:fff
 * @time:2022/2/25
 */
@Service
public class WagesService extends ServiceImpl<WagesMapper, Wages> {
    @Resource
    WorkOrderService workOrderService;
    @Resource
    WorkReportService workReportService;
    @Resource
    MissionService missionService;
    @Resource
    UnitService unitService;
    @Resource
    ProductService productService;
    @Resource
    ProcessesService processesService;
    @Resource
    UserService userService;
    @Resource
    CustomFieldService customFieldService;
    @Resource
    MatchingRuleService matchingRuleService;
    @Resource
    DimensionCombinationService dimensionCombinationService;
    @Resource
    WagesService wagesService;

    public Wages workReportGetWages(WageReportVo vo) throws ExecutionException, InterruptedException {
        WorkOrder wo = workOrderService.getOne(new QueryWrapper<WorkOrder>().eq("code", vo.getWordOrderCode()));
        MissionListResp mlr = missionService.getBaseMapper().getMissionOne(new QueryWrapper<MissionListResp>().eq("m.id",vo.getMissionId()));
        Product product = productService.getById(wo.getProductId());
        Unit unit = unitService.getById(product.getUnitId());
        Processes processes = processesService.getOne(new QueryWrapper<Processes>().eq("code",mlr.getProcessCode()));
        if (Objects.isNull(vo.getUserId())){
            vo.setUserId(LoginUtil.getLoginUserId().toString());
        }
        User user = userService.getById(vo.getUserId());
        if(unit!=null){
            mlr.setProductUnit(unit.getName());
        }
        List<Wages> wages = wagesService.list(new QueryWrapper<Wages>().eq("del_flag",1).orderByDesc("id"));
        Wages wage = new Wages();
        List<DimensionCombination> dimensionCombinations = dimensionCombinationService.list();
        for (DimensionCombination d : dimensionCombinations) {
            if(wage!=null && wage.getId()!=null){
                break;
            }
            //循环维度组合 一个一个匹配  有终止循环返回 没有就 按照优先级再循环匹配
            String combination = d.getCombination();
            List<MatchingRule> list = new ArrayList<>();
            Arrays.asList(combination.split(",")).forEach(s -> {
                String[] split = s.split("\\.");
                MatchingRule matchingRule = matchingRuleService.getOne(new QueryWrapper<MatchingRule>().eq("attribute", split[1]).eq("state",1));
                list.add(matchingRule);
            });
            if(!CollectionUtils.isEmpty(wages)){
                ExecutorService service = Executors.newFixedThreadPool(wages.size());
                for (Wages w : wages) {
                    User finalUser = user;
                    Future future = service.submit(new Callable() {
                        @Override
                        public Object call() throws Exception {
                            if(StringUtil.isNotBlank(w.getOther())){
                                int a = 0;
                                Map<String,Object> otherMap = JSONObject.parseObject(w.getOther());
                                for (MatchingRule m : list) {
                                    if(StringUtil.isNotBlank(m.getBusinessObject()) && !StringUtils.isNumeric(m.getCusField())){
                                        if(m.getCusField().equals("pricing")){
                                            if(otherMap!=null && !otherMap.isEmpty() && otherMap.get(m.getCusField())!=null && otherMap.get(m.getCusField()).toString().equals(vo.getPricing().toString())){
                                                a++;
                                                continue;
                                            }
                                        }else if (m.getCusField().equals("userId")){
//                                    if(vo.getUserId()!=null && vo.getUserId().toString().equals(otherMap.get(m.getCusField()).toString())){
//                                        a++;
//                                        continue;
//                                    }
                                            if(otherMap!=null && !otherMap.isEmpty() && otherMap.get(m.getCusField())!=null && finalUser !=null && finalUser.getAccount().equals(otherMap.get(m.getCusField()).toString())){
                                                a++;
                                                continue;
                                            }
                                        }else {
                                            Field field = mlr.getClass().getDeclaredField(m.getCusField());
                                            field.setAccessible(true);
                                            if(otherMap.get(m.getCusField())!=null && otherMap.get(m.getCusField()).equals(field.get(mlr).toString())){
                                                a++;
                                                continue;
                                            }
                                        }
                                    }else if(StringUtil.isNotBlank(m.getBusinessObject()) && StringUtils.isNumeric(m.getCusField())){
                                        List<CustomFieldVo> vos = new ArrayList<>();
                                        if(m.getBusinessObject().equals("工单")){
                                            if(StringUtil.isNotBlank(wo.getOther())){
                                                vos = customFieldService.handleCustomFieldForList(wo.getOther());
                                            }
                                        }else if(m.getBusinessObject().equals("产品")){
                                            if(StringUtil.isNotBlank(product.getOther())){
                                                vos = customFieldService.handleCustomFieldForList(product.getOther());
                                            }
                                        }else if(m.getBusinessObject().equals("工序")){
                                            if(StringUtil.isNotBlank(processes.getOther())){
                                                vos = customFieldService.handleCustomFieldForList(processes.getOther());
                                            }
                                        }else if(m.getBusinessObject().equals("用户")){
                                            if(finalUser !=null && StringUtil.isNotBlank(finalUser.getOther())){
                                                vos = customFieldService.handleCustomFieldForList(finalUser.getOther());
                                            }
                                        }else if(vo.getCustom()!=null && !vo.getCustom().isEmpty() &&
                                                vo.getCustom().get(m.getCusField())!=null && otherMap.get(m.getCusField())!=null
                                                && vo.getCustom().get(m.getCusField()).equals(otherMap.get(m.getCusField()))){
                                            a++;
                                            continue;
                                        }
                                        if(!CollectionUtils.isEmpty(vos)){
                                            CustomFieldVo cfv = vos.stream().filter(f->f.getCustomFieldId().toString().equals(m.getCusField())).findAny().orElse(null);
                                            if(otherMap.get(m.getCusField())!=null && cfv!=null && cfv.getValue().equals(otherMap.get(m.getCusField()))){
                                                a++;
                                                continue;
                                            }
                                        }
                                    }
                                }
                                if(a==list.size()){
                                    service.shutdownNow();
                                    return w;
                                }
                            }
                            return null;
                        }
                    });
                    if(future.get()!=null){
                        wage = (Wages) future.get();
                        break;
                    }
                }
            }
        }
        return wage;
    }


}
